package cn.yuanqiao.web.controller.manage;

import cn.yuanqiao.common.constant.SysContants;
import cn.yuanqiao.common.constant.UserConstants;
import cn.yuanqiao.common.core.domain.R;
import cn.yuanqiao.common.core.domain.entity.ManageMenu;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.core.controller.BaseController;
import cn.yuanqiao.common.core.domain.AjaxResult;
import cn.yuanqiao.common.annotation.Log;
import cn.yuanqiao.common.enums.BusinessType;
import cn.yuanqiao.common.utils.SecurityUtils;

import cn.yuanqiao.manage.service.IManageMenuService;
import cn.yuanqiao.system.domain.vo.RouterVo;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 菜单信息
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/manage/menu")
public class ManageMenuController extends BaseController
{
    @Resource
    private IManageMenuService manageMenuService;

    /**
     * 获取菜单列表
     */
    @GetMapping("/list")
    public AjaxResult list(ManageMenu menu)
    {
        Long userId = SecurityUtils.getUserId();
        List<ManageMenu> menus = manageMenuService.selectMenuList(menu, userId);
        return success(menus);
    }

    /**
     * 根据菜单编号获取详细信息
     */
    @GetMapping(value = "/{menuId}")
    public AjaxResult getInfo(@PathVariable Long menuId)
    {
        return success(manageMenuService.selectMenuById(menuId));
    }

    /**
     * 获取菜单下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(ManageMenu menu)
    {
        Long userId = SecurityUtils.getUserId();
        List<ManageMenu> menus = manageMenuService.selectMenuList(menu, userId);
        return success(manageMenuService.buildMenuTreeSelect(menus));
    }

    /**
     * 加载对应角色菜单列表树
     */
    @GetMapping(value = "/roleMenuTreeselect/{roleId}")
    public AjaxResult roleMenuTreeselect(@PathVariable("roleId") Long roleId)
    {
        Long userId = SecurityUtils.getUserId();

        List<ManageMenu> menus = manageMenuService.selectMenuList(userId);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", manageMenuService.selectMenuListByRoleId(roleId));
        ajax.put("menus", manageMenuService.buildMenuTreeSelect(menus));
        return ajax;
    }


    /**
     * 获取三员列表
     */
    @GetMapping(value = "/getTemplateMenuIds/{isSanyuan}/{tenantCode}")
    public R<Long[]> getTemplateMenuIds(@PathVariable("isSanyuan") String isSanyuan, @PathVariable("tenantCode") String tenantCode)
    {
        Long[] menuIds = manageMenuService.getTemplateMenuIds(isSanyuan,tenantCode);
        return R.ok(menuIds);
    }

    /**
     * 新增菜单
     */
    @Log(title = "菜单管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody ManageMenu menu)
    {
        menu.setTenantCode(SecurityUtils.getTenantCode());
        menu.setType("1");
        if (!manageMenuService.checkMenuNameUnique(menu))
        {
            return error("新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        }
        else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath()))
        {
            return error("新增菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        menu.setCreateBy(SecurityUtils.getUsername());
        int i = manageMenuService.insertMenu(menu);
        /*SysUser sysUser = sysUserService.selectUserById(SecurityUtils.getUserId());
        List<SysRole> roles = sysUser.getRoles();
        for (SysRole role : roles) {
            role.setMenuIds(new Long[]{menu.getMenuId()});
            sysRoleService.insertRoleMenu(role);
        }*/
        return toAjax(i);
    }

    /**
     * 修改菜单
     */
    @Log(title = "菜单管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody ManageMenu menu)
    {
        if (!manageMenuService.checkMenuNameUnique(menu))
        {
            return error("修改菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        }
        else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath()))
        {
            return error("修改菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        else if (menu.getMenuId().equals(menu.getParentId()))
        {
            return error("修改菜单'" + menu.getMenuName() + "'失败，上级菜单不能选择自己");
        }
        menu.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(manageMenuService.updateMenu(menu));
    }

    /**
     * 删除菜单
     */
    @Log(title = "菜单管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{menuId}")
    public AjaxResult remove(@PathVariable("menuId") Long menuId)
    {
        if (manageMenuService.hasChildByMenuId(menuId))
        {
            return warn("存在子菜单,不允许删除");
        }
        return toAjax(manageMenuService.deleteMenuById(menuId));
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        String userType = SecurityUtils.getUserType();
        List<ManageMenu> menus = null;
        if(SysContants.MANAGEDEPTFLAG.equals(userType)){
            menus = manageMenuService.selectMenuTreeByUserRoleKey(SysContants.MANAGEROLEFLAG);
        }else{
            Long userId = SecurityUtils.getUserId();
            menus = manageMenuService.selectMenuTreeByUserId(userId);
        }
        List<RouterVo> routerVos = manageMenuService.buildMenus(menus);
        return success(routerVos);
    }
}